package processor

import (
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"study/14_practice_chat/common"
	"study/14_practice_chat/utils"
)

type ServerUserProcessor struct {
	Conn net.Conn
}

func (this *ServerUserProcessor) Login(request common.RequestBody) (err error) {
	// 获得data并反序列化成 LogInMessage
	jsonString := request.Data
	var logInMessage common.LogInMessage
	err = json.Unmarshal([]byte(jsonString), &logInMessage)
	if err != nil {
		fmt.Println("deserialized login message error!", err)
		return
	}
	// 判断用户名密码
	var response common.ResponseBody
	if logInMessage.Name == "root" && logInMessage.Password == "123456" {
		response.Code = 200
		response.Msg = "ok"
	} else {
		response.Code = 4001
		response.Msg = "username or password error!"
		err = errors.New(response.Msg)
	}
	// 将登陆状态返回给客户端
	errResp := utils.WriteResponse(this.Conn, response)
	if errResp != nil {
		fmt.Println("send login login response error!", errResp)
		err = errResp
		return
	}
	return
}
